package com.shouchuang.websocketserver;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import android.util.Log;

public class ServerService extends Service {
	private Server server;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        server = new Server();
        server.start();

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent nfIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE);
        String channelId = "WebSocketService";
        NotificationChannel notificationChannel = new NotificationChannel(channelId, "服务通知", NotificationManager.IMPORTANCE_HIGH);
        notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        notificationManager.createNotificationChannel(notificationChannel);
        Notification notification = new NotificationCompat.Builder(this, channelId)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("服务正在运行")
                .setContentText("WebSocketServer")
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setOngoing(true)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setChannelId(channelId)
                .build();
        startForeground(1, notification);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        try{
            server.stop();
            Log.d("WebSocketServer", "服务已停止");
        }
        catch(Exception ex){
            Log.e("WebSocketServer", ex.toString());
        }
        stopForeground(true);
    }
}